package com.bluexmicro.ota2.ui.screen.yika

import android.annotation.SuppressLint
import android.text.TextUtils
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.bluexmicro.bluetooth.toUInt8
import com.bluexmicro.ota2.picker.file.LaunchFilePicker
import com.bluexmicro.ota2.ui.custom.DisplayItem
import com.bluexmicro.ota2.ui.custom.KeepScreenOnView
import com.bluexmicro.ota2.ui.custom.SubTopBar
import com.bluexmicro.ota2.ui.custom.formatBytes
import com.bluexmicro.ota2.ui.custom.stepContent
import com.bluexmicro.ota2.ui.custom.stepTitle
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState

@SuppressLint("MissingPermission")
@OptIn(ExperimentalMaterial3Api::class, ExperimentalPermissionsApi::class)
@Composable
fun YiKaCheckScreen(navHostController: NavHostController) {

    val viewModel: YiKaCheckViewModel = viewModel()
    val context = LocalContext.current

    val items = remember {
        viewModel.items
    }

    var rssiThreshold by remember {
        mutableStateOf(-100)
    }

    val checking = remember {
        viewModel.checking
    }

    val ver = remember {
        viewModel.ver
    }

    val type = remember {
        viewModel.type
    }


    val permissionState = rememberMultiplePermissionsState(permissions = viewModel.permissions) {

    }

    LaunchedEffect(Unit) {
        permissionState.launchMultiplePermissionRequest()
    }


    val filePicker = rememberLauncherForActivityResult(contract = LaunchFilePicker(), onResult = {
        if (it != null) {
            viewModel.onFileSelected(context, it)
        }
    })


    Scaffold(
        topBar = {
            SubTopBar(title = "批量固件升级(DFU)") {
                navHostController.popBackStack()
            }
        }
    ) {
        LazyColumn(
            modifier = Modifier.padding(it),
            contentPadding = PaddingValues(16.dp),
        ) {


            stepTitle(1, "选择升级包（zip压缩包）", items.value.isNotEmpty())

            stepContent {
                Card {
                    for (entry in items.value.withIndex()) {
                        val title = entry.value.run {
                            "${idx.toUInt8()}: $fileName"
                        }
                        val desc = "Size: ${formatBytes(entry.value.rawData.size.toLong())}"
                        DisplayItem(title, desc)
                        if (entry.index < items.value.lastIndex) {
                            Divider(thickness = Dp.Hairline)
                        }
                    }
                }
                Spacer(modifier = Modifier.height(8.dp))
                Button(onClick = { filePicker.launch("zip") }) {
                    Text(text = "选择")
                }
                KeepScreenOnView(keepOn = true, modifier = Modifier.size(8.dp))
            }

            stepTitle(2, "过滤条件", true)

            item {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 32.dp, vertical = 16.dp)
                ) {
                    Text(text = "限制信号强度大于阈值（${rssiThreshold}dbm）")
                    Spacer(modifier = Modifier.height(8.dp))
                    Slider(
                        value = rssiThreshold + 127f,
                        onValueChange = { cur ->
                            rssiThreshold = cur.toInt() - 127
                        },
                        valueRange = 0f..127f,
                        enabled = !checking.value
                    )
                    Text(text = "产品ID：${type.value}")
                    Text(text = "版本：V${ver.value}")
                    Spacer(modifier = Modifier.height(16.dp))
                    Button(
                        onClick = {
                            if (checking.value) {
                                viewModel.stop()
                            } else {
                                viewModel.check(context, rssiThreshold)
                            }
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(56.dp),
                        enabled = items.value.isNotEmpty() && type.value != null && ver.value != null
                    ) {
                        val txt = if (checking.value) {
                            "停止检测"
                        } else {
                            "开始检测版本"
                        }
                        Text(text = txt)
                    }
                }
            }

            item {
                Spacer(modifier = Modifier.height(64.dp))
            }
        }
    }


}